package com.skrumtious;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.skrumtious.action.WebAction;
import com.skrumtious.action.WebRequest;
import com.skrumtious.action.WebResponse;
import com.skrumtious.util.ReflectionClass;
import com.skrumtious.util.StringUtil;


/**
 * The main servlet.
 * 
 * @author Tony
 *
 */
public class SkrumtiousServlet extends HttpServlet {
	
	
	/**
	 * SUID
	 */
	private static final long serialVersionUID = 8561982453090483785L;

	/**
	 * Action parameter
	 */
	public static final String ACTION = "action";
	
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String action = req.getParameter(ACTION);
		if ( ! StringUtil.isEmpty(action) ) {
			WebRequest request = new WebRequest(req, resp);
			try {
				/*
				 * Execute the action
				 */
				WebAction webAction = ReflectionClass.createObject(action);				
				WebResponse response = webAction.doAction(request);
		
				handleWebResponse(req, resp, response);
			}
			catch(Exception e) {
				/* TODO - handle error */
				System.out.println(e);
			}
		}
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	/**
	 * Handles a {@link WebResponse}.
	 * 
	 * @param req
	 * @param resp
	 * @param response
	 * @throws Exception
	 */
	private void handleWebResponse(HttpServletRequest req, HttpServletResponse resp, WebResponse response) throws Exception {
		if ( response.isForward() ) {
			req.getRequestDispatcher(response.getFileName()).forward(req, resp);
		}
		else if ( response.isRedirect() ) {
			resp.sendRedirect(response.getFileName());
		}
	}
}
